package org.adorsys.aderp.aderplogin.security;

import java.util.List;

import org.adorsys.aderp.aderplogin.client.ClientDetailsHelper;
import org.adorsys.aderp.aderplogin.domain.AderpClientDetail;
import org.adorsys.aderp.aderplogin.repository.AderpClientDetailRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * This local client detail service is not available outside of this module.
 * 
 * Operation provided here are only meaning full for the business logic of this
 * module.
 * 
 * This is also why we will not provide any service interface.
 * 
 * @author francis
 * 
 */
@Service
@Transactional
public class LocalClientDetailServiceImpl implements ClientDetailsService {

	@Autowired
	private AderpClientDetailRepository aderpClientDetailRepository;

	@Override
	public ClientDetails loadClientByClientId(String clientId)
			throws OAuth2Exception {
		if (StringUtils.isBlank(clientId)) {
			throw new InvalidClientException("Client with id not found");
		}

		List<AderpClientDetail> clients = aderpClientDetailRepository
				.findByClientId(clientId);
		if (clients.isEmpty())
			throw new InvalidClientException("Client with id not found");

		AderpClientDetail clientDetail = clients.iterator().next();
		return ClientDetailsHelper.createClientDetails(clientDetail);
	}
}
